package com.ctgu.springstart.exception;

import com.ctgu.springstart.util.Result;
import com.ctgu.springstart.util.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalControllerAdvice {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalControllerAdvice.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultException(HttpServletRequest request, Exception e){
        LOG.error("url:{},msg:{}", request.getRequestURL(), e.getMessage());
        return Result.builder()
                .code(ResultEnum.EXCEPTION.getCode())
                .message(ResultEnum.EXCEPTION.getMsg())
                .build();
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Object myException(HttpServletRequest request,MyException e){
        Integer code=e.getCode();
        String message=e.getMessage();

        LOG.error("define url:{},define msg:{}", request.getRequestURL(), e.getMessage());
        if(e.getCode()==null && e.getMessage() == null){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error/error.html");
            modelAndView.addObject("msg", e.getMessage());
            return modelAndView;
        }
        if (e.getCode()==null){
            code=ResultEnum.EXCEPTION.getCode();
        }
        if (e.getMessage()==null){
            message=ResultEnum.EXCEPTION.getMsg();
        }
        return Result.builder()
                .code(code)
                .message(message)
                .build();
    }
}